const context = "";
const host = 'https://' + window.location.host + context;
// const host = 'http://' + window.location.host + context;
const loginPage = host + '/index.html';
const fileUrl = "https://weiyun.mitaiot.com/mita/";
const gldUrl = "https://weiyun.mitaiot.com/pages/index";
const xhrReadyState = [
    {desc: '未初始化 未调用send方法'},
    {desc: '正在载入 已调用send方法，正在发送数据'},
    {desc: '已经载入 已调用send方法，数据发送完成'},
    {desc: '交互 正在解析响应内容'},
    {desc: '完成 响应内容解析完成'}
];

function getJson(url, params, method, success) {
    $.ajax({
        url: host + url,
        data: params,
        method: method,
        async: true,
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('token', sessionStorage.getItem("token"));
        },
        success: function (data) {
            if (data['code'] == 401) {
                myAlert('警告', data['message'], function () {
                    top.location.href = loginPage;
                });
            } else {
                success(data);
            }
        }, error: function (xhr) {
            printXHRErrorInfo(xhr);
        }
    });
}

function getJson4Multipart(url, params, method, success) {
    $.ajax({
        url: host + url,
        data: params,
        method: method,
        async: false,
        processData: false,
        contentType: false,
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        },
        success: function (data) {
            if (data['code'] == 401) {
                alert(data['message']);
                top.location.href = loginPage;
            }
            success(data);
        }, error: function (xhr) {
            printXHRErrorInfo(xhr);
        }
    });
}

function buildSelectNoData(select, dataList, text, value, msg, current, deal) {
    $(select).empty();
    createElementNoData("option", select, msg, 0);
    if (dataList && dataList.length > 0) {
        dataList.map(function (item) {
                var option = createElement("option", select, item[text], item[value]);
                if (item[value] == current) {
                    $(option).attr("selected", "selected");
                }
                if (deal) {
                    deal(option, item);
                }
        });
    }
}

function createElementNoData(type, parent, text, value) {
    if (!type) {
        throw 'type cannot be null';
    }
    var element = document.createElement(type);
    if (!isNull(text)) {
        $(element).text(text);
    }
    $(element).val(value);
    if (parent) {
        $(parent).append(element);
    }
    return element;
}

function createElement(type, parent, text, value) {
    if (!type) {
        throw 'type cannot be null';
    }
    var element = document.createElement(type);
    if (!isNull(text)) {
        $(element).text(text);
    }
    if (!isNull(value)) {
        $(element).val(value);
    }
    if (parent) {
        $(parent).append(element);
    }
    return element;
}

function buildSelect(select, dataList, text, value, current, deal) {
    $(select).empty();
    createElement("option", select, '请选择', null);
    if (dataList && dataList.length > 0) {
        dataList.map(function (item) {
            var option = createElement("option", select, item[text], item[value]);
            if (item[value] == current) {
                $(option).attr("selected", "selected")
            }
            if (deal) {
                deal(option, item)
            }
        });
    }
}

function buildSelectTwo(select, dataList, text, value, current, deal) {
    $(select).empty();
    if (dataList && dataList.length > 0) {
        dataList.map(function (item) {
            var option = createElement("option", select, item[text], item[value]);
            if (item[value] == current) {
                $(option).attr("selected", "selected")
            }
            if (deal) {
                deal(option, item)
            }
        });
    }
}

function buildList(list, dataList, deal) {
    $(list).empty();
    if (dataList && dataList.length > 0) {
        dataList.map(function (item) {
            var li = createElement('li', list, null, null);
            if (deal) {
                deal(li, item);
            }
        })
    }

}

function buildTable(table, titleList, labelList, dataList, deal) {
    $(table).empty();
    var thead = createElement('thead', table, null, null);
    var theadTr = createElement('tr', thead, null, null);
    var tbody = createElement('tbody', table, null, null);
    titleList.map(function (title) {
        createElement('th', theadTr, title, null);
    });
    if (dataList.length > 0) {
        dataList.map(function (item) {
            var tr = createElement('tr', tbody, null, null);
            labelList.map(function (label) {
                var td = createElement('td', tr, item[label], null);
                if (deal) {
                    deal(td, label, item);
                }
            });
        });
    } else {
        var tr = createElement('tr', tbody, null, null);
        var td = createElement('td', tr, '无数据', null);
        $(td).css('text-align', 'center');
        $(td).attr('colspan', titleList.length);
        $(td).addClass('wsj');
    }
}

function appendTableData(table, labelList, dataList, deal) {
    var tbody = $(table).find('tbody');
    dataList.map(function (item) {
        var tr = createElement('tr', tbody, null, null);
        labelList.map(function (label) {
            var td = createElement('td', tr, item[label], null);
            if (deal) {
                deal(td, label, item);
            }
        });
    });
}

function getSelectValue(select) {
    return $(select).find('option:selected').attr('value');
}

function getDate(ms) {
    var d = new Date();
    if (ms !== null && ms !== '') {
        d.setTime(ms);
    }
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var week = d.getDay();

    var hour = d.getHours();
    var minute = d.getMinutes();
    var second = d.getSeconds();

    var date = year + '-';
    if (month < 10) {
        date += '0';
    }
    date += month + '-';
    if (day < 10) {
        date += '0';
    }
    date += day + '';

    var time = '';
    if (hour < 10) {
        time += '0';
    }
    time += hour + ':';
    if (minute < 10) {
        time += '0';
    }
    time += minute + ':';
    if (second < 10) {
        time += '0';
    }
    time += second;

    var _week = '';
    switch (week) {
        case 0:
            _week = '星期日';
            break;
        case 1:
            _week = '星期一';
            break;
        case 2:
            _week = '星期二';
            break;
        case 3:
            _week = '星期三';
            break;
        case 4:
            _week = '星期四';
            break;
        case 5:
            _week = '星期五';
            break;
        case 6:
            _week = '星期六';
            break;
    }

    return {
        year: function () {
            return year;
        },
        month: function () {
            return month;
        },
        day: function () {
            return day;
        },
        date: function () {
            return date;
        },
        time: function () {
            return time;
        },
        datetime: function () {
            return date + ' ' + time;
        },
        week: function () {
            return week;
        },
        datetime_full: function () {
            return date + ' ' + _week + ' ' + time;
        }
    };
}

function getWeek() {
    var today = new Date();
    var first_day = new Date();
    first_day.setMonth(0);
    first_day.setDate(1);
    var offset = 7 - first_day.getDay();//偏移量
    var day = Math.ceil((today - first_day) / (24 * 60 * 60 * 1000)) + 1;
    var week = Math.ceil((day - offset) / 7) + 1;
    var year = today.getFullYear();
    return {
        year: function () {
            return year;
        },
        day: function () {
            return day;
        },
        week: function () {
            return week;
        }
    };
}

function formatDatetime(datetime) {
    var date = new Date();
    date.setYear(datetime['year']);
    date.setMonth(parseInt(datetime['month']) - 1);
    date.setDate(datetime['date']);
    date.setHours(datetime['hours']);
    date.setMinutes(datetime['minutes']);
    date.setSeconds(datetime['seconds']);
    return date;
}

function Page(label, callback) {
    var currentPage = 1;
    var pageCount = 1;

    function change(val) {
        if (val) {
            currentPage += val;
        }
        if (currentPage > pageCount) {
            currentPage = pageCount;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }
        callback(currentPage);
    }

    return {
        next: function () {
            change(1);
        },
        previous: function () {
            change(-1);
        },
        goto: function (_currentPage) {
            currentPage = _currentPage;
            change();
        },
        set: function (_currentPage, _pageCount) {
            currentPage = _currentPage;
            pageCount = _pageCount;
        },
        value: function () {
            return currentPage;
        },
        resetPageNumber: function (pageNumber) {
            $(pageNumber).empty();

            if (currentPage < 4) {
                for (var i = 1; i <= (pageCount < 5 ? pageCount : 5); i++) {
                    var num = createElement('a', label, i);
                    $(num).click(function () {
                        page.goto(i)
                    });
                    if (i == currentPage) {
                        $(num).addClass('current');
                    }
                }
            } else if (currentPage > 3 && pageCount - currentPage > 2) {
                for (var i = -2; i < 3; i++) {
                    var num = createElement('a', label, currentPage + i);
                    $(num).click(function () {
                        page.goto(currentPage + i)
                    });
                    if (i == 0) {
                        $(num).addClass('current');
                    }
                }
            } else {
                for (var i = 4; i >= 0; i--) {
                    var num = createElement('a', $('#pageNumber'), pageCount - i);
                    $(num).click(function () {
                        page.goto(pageCount - i)
                    });
                    if ((pageCount - i) == currentPage) {
                        $(num).addClass('current');
                    }
                }
            }
        }
    }
}

function isNull(o) {
    return o === '' || o === null || o === undefined;
}

function resetForm(form) {
    $(form).find('[name]:text').each(function () {
        $(this).val('');
    });
    $(form).find('[name]:radio,[name]:checkbox').each(function () {
        $(this).removeAttr('checked');
    });
    $(form).find('option').each(function () {
        $(this).removeAttr('selected');
    });
}

function printXHRErrorInfo(xhr) {
    var resp = xhr['responseJSON'];
    if (resp) {
        console.error('请求路径: ' + resp['path']);
        console.error('请求时间: ' + getDate(resp['timestamp']).datetime());
        console.error('请求状态: ' + xhrReadyState[xhr.readyState]['desc']);
        console.error('响应状态: ' + resp['status']);
        console.error('错误信息: ' + resp['error']);
        console.error('堆栈信息: \n' + resp['trace']);
    }
}

function formValidator(form) {
    var list = [];
    $(form).find('input').each(function () {
        if (isNull($(this).val())) {
            list.push(this)
        }
    });
    return list;
}

